const Router = require('koa-router');
const router = new Router({
    prefix: '/v1/classic'
});
const {
    Auth
} = require('../../../middlewares/auth')

const {
   Flow
} = require('../../models/flow')

const {
    Art
} = require('../../models/art')

const {
    Favor
} = require('../../models/favor')

const {
    PositiveIntegerValidator, ClassicValidator
} = require('../../validators/validator')

// 获取最新一期期刊的接口
router.get('/latest', new Auth().m, async (ctx, next) => {
    const flow =await Flow.findOne({
        order: [
            ['index', 'DESC']
        ]
    });
    const art = await Art.getData(flow.art_id, flow.type);
    const likeLatest = await Favor.userLikeIt(flow.art_id, flow.type, ctx.auth.uid);
    art.setDataValue('index', flow.index);
    art.setDataValue('like_status', likeLatest);
    ctx.body = art
});

// 获取下一期期刊的接口
router.get('/:index/next', new Auth().m, async (ctx) => {
    const v = await new PositiveIntegerValidator().validate(ctx, {
        id: 'index'
    })
    const index = parseInt(v.get('path.index'));
    const flow = await Flow.findOne({
        where: {
            index: index + 1
        }
    })
    ctx.body = await getBodyNews(flow, ctx.auth.uid);
})

// 获取上一期期刊的接口
router.get('/:index/previous', new Auth().m, async (ctx, next) => {
    const v = await new PositiveIntegerValidator().validate(ctx, {
        id: 'index'
    });
    const index = parseInt(v.get('path.index'));
    const flow = await Flow.findOne({
        where: {
            index: index - 1
        }
    })
    ctx.body = await getBodyNews(flow, ctx.auth.uid);
})

// 获取点赞信息
router.get('/:type/:id/favor', new Auth().m, async (ctx, next) => {
    const v = await new ClassicValidator().validate(ctx);
    const id = parseInt(v.get('path.id'));
    const type = parseInt(v.get('path.type'));
    const art = await Art.getData(id, type);
    if(!art) {
       throw new global.errs.Notfound();
    }
    const like = await Favor.userLikeIt(id, type, ctx.auth.uid);
    ctx.body = {
        fav_nums: art.fav_nums,
        like_status: like
    }
})

//获取到一个用户的点赞数的统计
router.get('/favor', new Auth().m, async (ctx, next) => {
   const uid = ctx.auth.uid;
   const art = await Favor.getMyClassicFavor(uid);
   ctx.body = art
})


async function getBodyNews(flow, uid) {
    if (!flow) {
        throw new global.errs.NotFound()
    }
    const art = await Art.getData(flow.art_id, flow.type)
    const likeNext = await Favor.userLikeIt(
        flow.art_id, flow.type, uid)
    art.setDataValue('index', flow.index)
    art.setDataValue('like_status', likeNext);
    return art
}

module.exports = router;
